package com.firefly.admin.common.listener;

import lombok.extern.slf4j.Slf4j;
import com.firefly.admin.common.constant.Constants;
import com.firefly.admin.common.utils.LogUtil;
import com.firefly.admin.common.utils.RedisUtil;
import com.firefly.admin.system.entity.FySystemUser;
import com.firefly.admin.system.service.FySystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    private FySystemUserService fySystemUserService;

    public RedisKeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            Object hGet = RedisUtil.hget(Constants.Redis.USER_TOKEN, message.toString());
            if (hGet != null) {
                RedisUtil.hdel(Constants.Redis.USER_TOKEN, message.toString());
                FySystemUser fySystemUser = fySystemUserService.findUserById(Long.valueOf(hGet.toString()));
                if (fySystemUser != null) {
                    LogUtil.saveSystemLogoutLog(fySystemUser.getUserName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
